package com.fengye.rabbit.order.rabbit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.rabbit.order.domain.UserOrder;
import com.fengye.rabbit.order.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月10日 2:10 下午
 */
@Component
@Slf4j
public class OrderPublisher {
    @Value("${order.producer.basic.exchange.name}")
    private String orderProducerExchangeName;

    @Value("${order.producer.basic.routing.key.name}")
    private String orderProducerRoutingKeyName;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public void sendMsg(MessageDTO dto) {
        try {
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.setExchange(orderProducerExchangeName);
            rabbitTemplate.setRoutingKey(orderProducerRoutingKeyName);

            rabbitTemplate.convertAndSend(dto, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageDTO.class);
                    messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    messageProperties.setExpiration(String.valueOf(3000));
                    return message;
                }
            });
            log.info("发送消息成功，orderNo={}", dto.getOrderNo());
        } catch (Exception e) {
            log.error("发送消息失败，orderNo={}", dto.getOrderNo(), e.fillInStackTrace());
        }
    }
}
